import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';

class FiveStartRatingWidget extends StatefulWidget {
  final int rating;
  final double starSize;
  final ValueChanged<int>? onRatingChanged;

  const FiveStartRatingWidget({
    super.key,
    required this.rating,
    required this.starSize,
    this.onRatingChanged,
  });

  @override
  State<FiveStartRatingWidget> createState() => _FiveStartRatingWidgetState();
}

class _FiveStartRatingWidgetState extends State<FiveStartRatingWidget> {
  int _currentRating = 0;

  @override
  void initState() {
    super.initState();
    _currentRating = widget.rating;
  }

  @override
  void didUpdateWidget(covariant FiveStartRatingWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.rating != widget.rating) {
      _currentRating = widget.rating;
    }
  }

  @override
  Widget build(BuildContext context) {
    final lightColor = AppTheme.shared.commonTipColor;
    final greyColor = AppTheme.shared.greyColor;
    return Row(
      children: List.generate(5, (index) {
        if (widget.onRatingChanged != null) {
          return SizedBox(
            width: widget.starSize + 8,
            height: widget.starSize + 8,
            child: Center(
              child: IconButton(
                icon: Icon(
                  Icons.star,
                  color: index < _currentRating ? lightColor : greyColor,
                  size: widget.starSize,
                ),
                padding: EdgeInsets.zero,
                onPressed: () {
                  setState(() {
                    _currentRating = index + 1;
                  });
                  widget.onRatingChanged?.call(_currentRating);
                },
              ),
            ),
          );
        } else {
          return Icon(
            Icons.star,
            color: index < _currentRating ? lightColor : greyColor,
            size: widget.starSize,
          );
        }
      }),
    );
  }
}
